from django.shortcuts import render

# Create your views here.
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from backend.apps.recruit.models import City, Enterprise, Recruit
from backend.apps.recruit.serializers import CitySerializers, RecruitSerializers, EnterpriseSerializers, \
    EnterpriseSerializerSimple, RecruitSerializerSimple


# 职位的类视图
class RecruitViewSet(ModelViewSet):
    queryset = Recruit.objects.filter(state="1").order_by("-createtime")

    # 这个地方不知 是什么意思
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return RecruitSerializers
        else:
            return RecruitSerializerSimple

    # 职位收藏
    @action(methods=['post'], detail=True)
    def collect(self, request, pk):
        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None
        # 如果用户不是空 并且检测用户----这个是连接的那个地方
        if user is not None and user.is_authenticated:
            recruit = self.get_object()  # 获取根据pk显示的数据
            recruit.users.add(user)  # 添加进去表里
            recruit.save()  # 保存
            return Response({'success': True, 'message': '收藏成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
            pass

        # 取消收藏
    # 取消收藏
    @action(methods=['post'], detail=True)
    def cancelcollect(self, request, pk):
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            recruit = self.get_object()
            recruit.users.remove(user)
            recruit.save()
            return Response({'success': True, 'message': '取消收藏成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    # 职位详情
    @action(methods=["GET"], detail=True)
    def look(self,request,pk):
        # 1.获取数据
        jobs = self.get_object()
        # 2.序列化数据
        ser = self.serializer_class(jobs)
        # 3.返回数据
        return Response(ser.data)


    # 更新访问量
    @action(methods=["PUT"], detail=True)
    def visit(self, reuqest, pk):
        # 获取前端传递过来的pk
        sum = self.get_object()  # 根据pk参数查找queryset中的数据对象

        sum.visits += 1

        sum.save()
        return Response({'success': True, 'message': '更新成功'})

    # 搜索职位----我不懂这个地方
    @action(methods=["POST"], detail=False, url_path="search/city/keyword")
    def search_job(self, request):
        cityname = request.data.get('name')
        keyword = request.data.get('keyword')
        jobs = self.get_queryset()
        ret_jobs = []
        if not cityname and not keyword:
            ret_jobs = jobs
        elif cityname and not keyword:
            for job in jobs:
                if job.city == cityname:
                    ret_jobs.append(job)
        elif not cityname and keyword:
            for job in jobs:
                if job.jobname.lower().find(keyword.lower()) != -1:
                    ret_jobs.append(job)
        else:
            for job in jobs:
                if job.city == cityname and job.jobname.lower().find(keyword.lower()) != -1:
                    ret_jobs.append(job)

        serializer = self.get_serializer(instance=ret_jobs, many=True)
        return Response(serializer.data)

        pass

    # 最新职位
    @action(methods=["GET"], detail=False, url_path="search/latest")
    def get_latest_job(self, request):
        jobs = self.get_queryset()[0:4]
        serializer = self.get_serializer(instance=jobs, many=True)
        return Response(serializer.data)

    # 推荐的职位  GET方式  地址/recruits/search/recommend/
    @action(methods=["GET"], detail=False, url_path="search/recommend")
    def get_recommend_job(self, reqeust):
        # 1.获取数据
        recommend = self.get_queryset().order_by()[0:4]
        # 2.序列化数据
        ser = self.get_serializer(recommend, many=True)
        # 3.返回
        return Response(ser.data)
        pass


# 企业的类视图
class EnterpriseViewSet(ModelViewSet):
    queryset = Enterprise.objects.all()
    # 这个地方不知 是什么意思
    def get_serializer_class(self):
        if self.action == "retrieve":
            return EnterpriseSerializers
        else:
            return EnterpriseSerializerSimple

    # 企业详情
    @action(methods=["GET"], detail=True)
    def looks(self, request, pk):
        # 1.获取数据
        enter = self.get_object()
        # 2.序列化数据
        ser = self.serializer_class(enter)
        # 3.返回数据
        return Response(ser.data)
        pass

    # 收藏企业
    @action(methods=['post'], detail=True)
    def collect(self,request,pk):
        '''
        收藏企业 首先要获取用户，判断用户是否登入，然
        :param request:
        :return:
        '''
        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None
        # 如果用户不是空 并且检测用户
        if user is not None and user.is_authenticated:
            enterprise = self.get_object()  # 获取根据pk显示的数据
            enterprise.users.add(user)  # 添加进去表里
            enterprise.save()  # 保存
            return Response({'success': True, 'message': '收藏成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
            pass

    # 取消收藏
    @action(methods=['post'], detail=True)
    def cancelcollect(self, request, pk):
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            enterprise = self.get_object()
            enterprise.users.remove(user)
            enterprise.save()
            return Response({'success': True, 'message': '取消收藏成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    # 热门企业 /enterprise/search/hotlist/  GET方式
    @action(methods=["GET"], detail=False, url_path="search/hotlist")
    def hot(self, request):
        # 1.获取热门企业数据
        enter = self.get_queryset().order_by()[0:4]

        # 2.选择序列化器
        ser = self.get_serializer(enter, many=True)
        # 3.返回数据
        return Response(ser.data)
        pass

    # 增加企业的访问量 重写一个PUT的动作 路由是 /enterprise/{id}/visit/
    @action(methods=["PUT"], detail=True)
    def visit(self, reuqest, pk):
        # 获取前端传递过来的pk
        sum = self.get_object()  # 根据pk参数查找queryset中的数据对象

        sum.visits += 1

        sum.save()
        return Response({'success': True, 'message': '更新成功'})


# 城市的类视图
class CityViewSet(ModelViewSet):
    # ORM获取查询集
    queryset = City.objects.all()
    # 获取序列化器
    serializer_class = CitySerializers

    # 创建一个自定义 查询的动作,路由是 city/hotlist/
    @action(methods=["GET"], detail=False, url_path="hotlist")
    def hot_list(self, request):
        # 获取 后台要传过去的内容
        cities = City.objects.filter(ishot=1)  # 筛选热门城市
        # 获取需要序列化的内容
        ser = self.get_serializer(cities, many=True)
        return Response(ser.data)
